import { Effect, Reducer, Subscription, request } from 'umi';
import { herolist } from '@/api/wiki';
export interface HeroProps {
  id: number,
  name: string,
  name_loc: string,
  name_english_loc: string,
  primary_attr: number,
  complexity: number,
  index_img: string,
  top_img: string,
  top_video: string,
  crops_img: string
}

export interface HeroModelState {
  heroes: HeroProps[]
}

export interface HeroModelType {
  namespace: 'hero'
  state: HeroModelState,
  effects: {
    fetch:Effect
  }
  reducers: {
    save: Reducer<HeroModelState>
  }
  subscriptions: {setup:Subscription}
}

const HeroModel: HeroModelType = {
  namespace: 'hero',
  state: {
    heroes: []
  },
  effects: {
    *fetch({type,payload}, {put,call}){
      const data = yield request(herolist)
      
      const heroes = data.result.heroes

      yield put({
        type: 'save',
        payload: {
          heroes: heroes
        }
      })
    }
  },
  reducers: {
    save: function (state , action): HeroModelState {
      return {
        ...state,
        ...action.payload
      }
    }
  },
  subscriptions: {
    setup: function ({dispatch, history}): void | Function {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/hero') {
          dispatch({
            type: 'fetch'
          })
        }
      })
    }
  }
}
export default HeroModel